﻿using System.Linq;
using Loong.Runtime.Security;

namespace Loong.Runtime.Session
{
    public class ClaimsSession : ILoongSession
    {
        public long? UserId
        {
            get
            {
                var userIdClaim = PrincipalAccessor.Principal?.Claims.FirstOrDefault(c => c.Type == LoongClaimTypes.UserId);
                if (string.IsNullOrEmpty(userIdClaim?.Value))
                {
                    return null;
                }

                long userId;
                if (!long.TryParse(userIdClaim.Value, out userId))
                {
                    return null;
                }

                return userId;
            }
        }


        protected IPrincipalAccessor PrincipalAccessor { get; }

        public ClaimsSession(IPrincipalAccessor principalAccessor)
        {
            PrincipalAccessor = principalAccessor;
        }
    }
}
